<?php

declare(strict_types=1);

namespace app\admin\service;

use app\admin\model\CustomerLog as CustomerLogModel;
use app\common\exception\ThrowException;

class CustomerLog
{

    protected $return;
    protected $validate;
    protected $model;
    public function __construct()
    {
        $this->validate = new \app\admin\validate\Customer();
        $this->model = new CustomerLogModel();
        $this->return = [
            'code' => 500,
            'data' => [],
            'message' => ''
        ];
    }

    /**
     * @describe 记录用户操作日志
     * @author: Bobo
     * @date: 2024-08-01 15:35:48 
     * @param [string] @required $operate 操作类型 
     * @param [int] @required $c_id 用户id
     * @param [string] @required $msg 操作内容
     * @return void
     * @throws InvalidArgumentException 如果参数无效
     * @throws Exception 如果记录日志失败
     */

    public function logging(string $operate, int $c_id, string $msg)
    {
        // 输入验证
        if (empty($operate)) {
            throw new ThrowException([
                'msg' => '操作类型不能为空',
                'errorCode' => 0
            ]);
        }

        if ($c_id <= 0) {
            throw new ThrowException([
                'msg' => '用户ID必须为正整数',
                'errorCode' => 0
            ]);
        }

        if (empty($msg)) {
            throw new ThrowException([
                'msg' => '操作内容不能为空',
                'errorCode' => 0
            ]);
        }

        // 获取请求中的操作员信息
        $operator_id = request()->operator_id ?? 0;
        $operator_user = request()->operator_user ?? '系统操作';

        try {
            // 创建日志记录
            CustomerLogModel::create([
                'operate' => $operate,
                'c_id' => $c_id,
                'msg' => $msg,
                'operate_id' => $operator_id,
                'operate_name' => $operator_user,
            ]);
        } catch (\Exception $e) {
            // 记录异常日志
            error_log('记录用户操作日志失败: ' . $e->getMessage());
            throw new ThrowException([
                'msg' => '记录用户操作日志失败: ' . $e->getMessage(),
                'errorCode' => 0
            ]);
        }
    }


    /**
     * @describe 记录批量用户操作日志
     * @author: Bobo
     * @date: 2024-08-02 16:00:00
     * @param array $operations 操作数组，每个元素应包含 operate, c_id, msg
     * [
     *     ['operate' => 'add', 'c_id' => 1, 'msg' => '添加用户'],
     *     ['operate' => 'delete', 'c_id' => 2, 'msg' => '删除用户'],
     * ]
     * @return void
     * @throws ThrowException 如果参数无效或记录日志失败
     */
    public function batchLogging(array $operations)
    {
        if (empty($operations)) {
            throw new ThrowException([
                'msg' => '操作数组不能为空',
                'errorCode' => 0
            ]);
        }

        // 获取请求中的操作员信息
        $operator_id = request()->operator_id ?? 0;
        $operator_user = request()->operator_user ?? '系统操作';

        try {
            $logs = [];
            foreach ($operations as $operation) {
                // 验证每个操作的数据
                if (empty($operation['operate']) || empty($operation['c_id']) || empty($operation['msg'])) {
                    throw new ThrowException([
                        'msg' => '操作数据不完整',
                        'errorCode' => 0
                    ]);
                }

                if ($operation['c_id'] <= 0) {
                    throw new ThrowException([
                        'msg' => '用户ID必须为正整数',
                        'errorCode' => 0
                    ]);
                }

                $logs[] = [
                    'operate' => $operation['operate'],
                    'c_id' => $operation['c_id'],
                    'msg' => $operation['msg'],
                    'operate_id' => $operator_id,
                    'operate_name' => $operator_user,
                ];
            }

            // 批量创建日志记录
            $res = CustomerLogModel::insertAll($logs);
        } catch (\Exception $e) {
            // 记录异常日志
            error_log('批量记录用户操作日志失败: ' . $e->getMessage());
            throw new ThrowException([
                'msg' => '批量记录用户操作日志失败: ' . $e->getMessage(),
                'errorCode' => 0
            ]);
        }
    }



    /**
     * @describe
     * @author: Bobo
     * @date: 2024-10-09 11:30:59 
     * @param [type] @required
     * @return Renderable
     */
    public function getCustomerLog(int $customerId)
    {
        if (empty($customerId) || !is_int($customerId) || $customerId < 1) {
            return [];
        }

        $data =  $this->model
            ->field(' CONCAT(operate, " (", operate_name, ") ") as title,msg as info,create_time')
            ->where('c_id', $customerId)
            ->order('create_time', 'desc')
            ->select()
            ->toArray();

        return $data;
    }
}
